//线的数量
var lineNumber = 17;
//线的间距
var lines = 30;
//边框距离
var bors = 10;
//总长度
var alls = 500;

var context;

//内置对象
var innerObj;

//五子棋对象
/*
{
	id: "xxx",
	click: (x,y) => {
		
	}
}
*/
function GoBang(obj) {
    innerObj = obj;

    //初始化棋盘
    initBoard();
}

//初始化棋盘
function initBoard() {
    //获取画布div
    var mycanvasDiv = document.getElementById(innerObj.id);
    //给div设置画布
    mycanvasDiv.innerHTML = "<canvas id='mycanvas' width='500px' height='500px' style='background-color: saddlebrown;'></canvas>";

    var mycanvas = document.getElementById("mycanvas");
    //设置棋盘的点击事件
    mycanvas.onclick = canvasClick;
    //获取画布的会话环境
    context = mycanvas.getContext('2d');
    //绘制棋盘
    drawBoard();
}

//绘制棋盘的方法
function drawBoard() {
    //循环绘制棋盘线
    for (var i = 0; i < lineNumber; i++) {
        context.strokeStyle = "dimgray";
        context.moveTo(bors + i * lines, bors);//垂直方向画30根线，相距20px;
        context.lineTo(bors + i * lines, alls - bors);
        context.stroke();
        context.moveTo(bors, bors + i * lines);//水平方向画15根线，相距30px;棋盘为14*14；
        context.lineTo(alls - bors, bors + i * lines);
        context.stroke();
    }
}

//棋盘点击事件
function canvasClick(e) {
    var x = e.offsetX;
    var y = e.offsetY;

    //计算得到下棋的坐标
    var boardX = parseInt(x / lines);
    var boardY = parseInt(y / lines);

    //drawGo(boardX, boardY, 0);
    innerObj.click(boardX, boardY);
}

//绘制棋子
function drawGo(x, y, color) {
    context.beginPath();
    if (color == 0) {
        context.fillStyle = "#000000";
    } else {
        context.fillStyle = "#ffffff";
    }
    context.arc(bors + x * lines, bors + y * lines, 10, 0, 2 * Math.PI);//绘制棋子
    context.fill();
    context.closePath();
}